package cn.shutdown.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jiangwujie on 2016/7/26.
 */
public class MessageUtil {

    public static final String PARAM_RESULT = "result";

    /**
     * 消息类型 警告
     */
    public static final String TYPE_WARN = "warn";
    /**
     * 消息类型 信息
     */
    public static final String TYPE_MESSAGE = "message";

    /**
     * 生成返回消息map
     * @param messageType 消息类型 参见 MessageUtil.TYPE_WARN TYPE_MESSAGE
     * @param message 消息内容
     * @return
     */
    public static Map<String, Object> buildMessageMap(String messageType, String message) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("messageType", messageType);
        result.put("message", message);
        return result;
    }

    /**
     * 从request中获取消息组建request消息信息属性
     * @param request
     */
    public static void buildMessage(HttpServletRequest request) {
        String message = request.getParameter("message");
        if (StringUtils.isNotBlank(message)) {
            String messageType = request.getParameter("messageType");
            request.setAttribute(PARAM_RESULT, buildMessageMap(messageType, message));
        }
    }

    /**
     * 从mav中获取消息组建request消息信息属性
     * @param request
     */
    public static void buildModelAndViewMessage(HttpServletRequest request) {
        String message = request.getParameter("message");

        if (StringUtils.isNotBlank(message)) {
            String messageType = request.getParameter("messageType");
            request.setAttribute(PARAM_RESULT, buildMessageMap(messageType, message));
        }
    }

    public static void setModelAndViewMessage(ModelAndView mav, String messageType, String message) {
        mav.addObject(TYPE_MESSAGE, buildMessageMap(messageType, message));
    }

}
